﻿package manager
{
	import core.actor.core.BoneData;
	
	import flash.display.*;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import loader.LoadProxy;
	import loader.core.BaseServer;
	import loader.core.LoadFile;
	import loader.core.LoadType;
	
	import magics.MagicData;
	
	import map.GameMap;
	import map.MapImgInfo;
	import map.MapInfo;
	
	import resource.LoadResource;
	
	import utils.DisplayUtil;
	
	public class LoadManager 
	{
		public static var resourcePath:String = "../";
		
		public static var loaderServer:BaseServer;//加载资源
		public var parseServer:BaseServer;//2进制解析资源
		
		public static var loadedMap:Dictionary = new Dictionary();//加载过的地图
		private static var loadProxyMap:Dictionary = new Dictionary();//下载完成后要回调处理的
		
		public static var loadedImg:Dictionary = new Dictionary();// 加载过的零散图片
		
		
		public function LoadManager()
		{
			parseServer = new BaseServer(LoadType.PAR_SERVER,comHandler);
			loaderServer = new BaseServer(LoadType.RES_SERVER,receviePre);
		}
		
		public function receviePre(file:LoadFile):void{
			if(file.type == LoadType.LOAD_ANI || file.type == LoadType.LOAD_MAGIC_ANI || file.type == LoadType.LOAD_XML){
				if(LoadType.LOAD_TYPE == LoadType.MD5_LOAD){
				   file.data = parseServer.decode(file.data as ByteArray);//md5时需要解析xml文件
				}
				comHandler(file);
			}else{
				parseServer.load(file);//md5时需要解析xml文件
			}	
		}
		
		//加载完成某文件后的处理工作
		public function comHandler(file:LoadFile):void{
			switch(file.type){
				case LoadType.LOAD_MAP_TILE:recevieTile(file);break;
				case LoadType.LOAD_SWF:recevieSwf(file);break;
				case LoadType.LOAD_ANI:	 //动作文件
				case LoadType.LOAD_MAGIC_ANI:recevieAni(file);break;		 //动作文件
				case LoadType.LOAD_XML:recevieMapXml(file);break;
				case LoadType.LOAD_IMG:recevieImg(file);break;
			}
		}
		
		public static function loadImg(url:String):Bitmap{
			if(null != loadedImg[url] && null != loadedImg[url] && undefined != loadedImg[url].bitmapData){
				try{
					return loadedImg[url];
				}catch(e:Error){
					
				}
					
			}
			
			var file:LoadFile = getLoadFile(url,LoadType.LOAD_IMG);
			if(file!= null){
				loaderServer.load(file);
			}
			
			loadedImg[url] = new Bitmap();
			
			return loadedImg[url];
		}
		
		public static function recevieImg(file:LoadFile):void{
			var imgData:BitmapData = (file.data as Bitmap).bitmapData;
			if(null == imgData)
				return;
			
			var img:Bitmap = loadedImg[file.realUrl];
			
			if(null != img.bitmapData)
			{
				img.bitmapData.dispose();
				img.bitmapData = null;
			}
			
			img.bitmapData = imgData;
		}
		
		//加载地图  LoadType.LOAD_MAP_TILE 
		public static function loadMap(mapImg:MapImgInfo):BitmapData{
			if(loadedMap[mapImg.key]!= null && loadedMap[mapImg.key]!= undefined){
				try{
					return loadedMap[mapImg.key].clone();
				}catch(e:Error){
					//DebugLayer.print("clone error",mapImg.key);
					return null;
				}
			}
			
			var file:LoadFile = getLoadFile(mapImg.path,mapImg.loadType);
			if(file!= null){
				file.parm = mapImg.repeat;
				//loadmapServer.sendToClient(file);// 多开共用资源
				loaderServer.load(file);
			}
			return null;
		}
		
		//接受切块的地图(test)
		public static function recevieTile(file:LoadFile):void{
			
			var mapTileData:BitmapData = (file.data as Bitmap).bitmapData;
			//缓存加载上来的图
			if(file.parm == true){//需要平铺的单独处理
				mapTileData = DisplayUtil.repeatImg(mapTileData, MapInfo.width * 2, mapTileData.height);
			}
			
			var key:String = "|map,"+file.fileName;
			
			loadedMap[key] = mapTileData.clone();
			//更新到界面			
			var mapTile:Bitmap = GameMap.allMapImgData[key];
			if(mapTile != null){
				//清除马赛克图
				if(mapTile.bitmapData != null){
					mapTile.bitmapData.dispose();
					mapTile.bitmapData = null;
				}
				//加载上来的图
				if(mapTileData != null){
					mapTile.bitmapData = mapTileData;
				}
			}
		}
		
		//加载swf
		public static function loadSwf(url:String,loadProxy:LoadProxy):void{
			var file:LoadFile = getLoadFile(url,LoadType.LOAD_SWF,loadProxy.uid);
        	if(file!= null){
				loaderServer.load(file);
        	}
        	//test
        	/* if(loadProxy.char !=null){
        		trace("sl",loadProxy.uid,loadProxy.char.charData.cid,file);
        	} */
        	loadProxyMap[loadProxy.uid]=loadProxy;
		}
		//接受swf,(npc,骨骼 ，装备，技能，特效)
		public static function recevieSwf(file:LoadFile):void{
			loadedMap[file.realUrl] = file.data;
			//trace("ml",file.url);
		 	for(var key:Object in loadProxyMap){
		 		var loadProxy:LoadProxy = loadProxyMap[key] as LoadProxy;
		 		/* if(loadProxy.char !=null && loadProxy.uid == file.uid){
        			trace("el",file.url,file.uid,loadProxy.uid,loadProxy.char.charData.cid);
        		} */
        		//修正一个代理加载多个文件时，加载慢时，骨骼不对应的bug，原理同recevieAni
		 		if(loadProxy.uid == file.uid){
		 			loadProxy.setData(file.data,file.realUrl);
		 			return;
		 		}
		 	}
		}
		//加载动作或攻击效果xml
		public static function loadCharAction(url:String,loadProxy:LoadProxy):void{
            var file:LoadFile = getLoadFile(url,loadProxy.type,loadProxy.uid);
        	if(file!= null){
				loaderServer.load(file);
        	}
        	loadProxyMap[loadProxy.uid]=loadProxy;
		}
		
		//接受动作（ani）， 动作里有的包含了法术文件（ma）
		public static function recevieAni(file:LoadFile):void{
			var data:Object;
			if(file.type == LoadType.LOAD_ANI){
				data = BoneData.convertAtoF(file.data);
			}
			else if(file.type == LoadType.LOAD_MAGIC_ANI)
			{
				data = MagicData.convertAtoF(file.data);
			}
			LoadResource.loadedAction[file.realUrl] = data;
			for(var key:Object in loadProxyMap){
		 		var loadProxy:LoadProxy = loadProxyMap[key] as LoadProxy;
		 		//例如loadProxy先加载一个a.ani，再加载一个b.ani,a比b加载慢时。a回覆盖掉b的动作
		 		//修正保证后要加载的动作，不会被加载慢的动作覆盖
		 		if(loadProxy.uid == file.uid && file.realUrl ==loadProxy.url){
		 			loadProxy.setData(data,file.realUrl);
		 			return;
		 		}
			}
		}
		//初始加载文件
		public static function getLoadFile(url:String,type:int,uid:String=""):LoadFile{
        	var file:LoadFile = new LoadFile(url,type,uid);
			return file;
        }
		
		//加载地图配置
		public static function loadMapXml(url:String):String{
			if(loadedMap[url]!=null){//直接加载
				SceneManager.getInstance().mainScene.gameMap.initMap(loadedMap[url]);
			}
			var file:LoadFile = getLoadFile(url,LoadType.LOAD_XML);
			if(file!= null){
				loaderServer.load(file);
			}
			return null;
		}
		
		//接受地图配置
		public static function recevieMapXml(file:LoadFile):void{
			loadedMap[file.realUrl] = XML(file.data);
			SceneManager.getInstance().mainScene.gameMap.initMap(loadedMap[file.realUrl]);
		}
        
		//切换地图时清除上次加载的所有地图资源，防止跑了多个地图后内存增加量很大
		public static function destoryMap():void{
			//清地图的url,多开共用标识
			/*var map:Dictionary = loadmapServer.loadedUrlMap;
			for(var key:Object in map){
				map[key]=null;
				delete map[key];
			}*/
			//清地图的图片资源
			destoryByType("map");
			//todo :切地图时把当前地图的怪物骨骼都清除一下
		}
		
		//清某一类加载的资源
		public static function destoryByType(type:String):void{
			for(var key:Object in loadedMap){
				if(key.toString().indexOf(type) != -1){
					loadedMap[key]=null;
					delete loadedMap[key];
					//trace("mapPath=",key,key.toString().indexOf("map"));
				}
			}
		}
		
        public static function destory():void{
			destoryMap();
        }
        
	}
}
